package zh.demo.controller;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import zh.demo.utils.JsonUtils;
import zh.demo.utils.URLUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;


/**
 * Created by zhangheng on 2017/9/26.
 */
@RestController
@RequestMapping(value = "/wechat")
public class weChatAarticleList {

    @RequestMapping(value = "/wechatlist", method = RequestMethod.POST)
    public void doGet(HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("utf-8");
        String id = request.getParameter("id");
        String page = request.getParameter("page");
        String method = request.getParameter("method");
        if (StringUtils.isBlank(method))
            return;

        int pageIndex = 0;
        int fnId = 0;
        if (!StringUtils.isBlank(id)) {
            fnId = Integer.valueOf(id);
        }
        if(!StringUtils.isBlank(page)){
            pageIndex = Integer.valueOf(page);
        }

        try {
            response.getWriter().print(JsonUtils.getInstance().format(getList(fnId, pageIndex)));//
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public Map<String, Object> getList(int id, int index) {
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        Map<String, Object> res = new HashMap<>();
        try {
            String p = "pc_" + id;
            if (index > 1) {
                p = --index + "";
            }
            String url = "http://weixin.sogou.com/pcindex/pc/pc_" + id + "/" + p + ".html";
            Document doc = Jsoup.connect(url).ignoreContentType(true).timeout(5000).get();
            Elements es = doc.select("li");
            Map<String, String> d;
            for (Element element : es) {
                String img = element.select("div.img-box a img").attr("abs:src");
                String title = element.select("div.txt-box h3").text();
                String link = element.select("div.txt-box h3 a").attr("abs:href");
                String content = element.select("div.txt-box p.txt-info").text();
                String author = element.select("div.txt-box div.s-p a").text();
                String time = element.select("div.txt-box div.s-p span.s2").attr("t");
                String authorUrl = element.select("div.txt-box div.s-p a").attr("abs:href");
                d = new HashMap<>();
                d.put("img", img);
                d.put("title", title);
                d.put("content", content);
                d.put("author", author);
                d.put("time", time);
                d.put("link", link);
                d.put("authorUrl", authorUrl);
                list.add(d);
            }
            res.put("list",list);
            res.put("code",0);
        } catch (IOException e) {
            e.printStackTrace();
            res.put("code", 1);
        }
        return res;
    }
    public static void main(String[] args) {
        //getTypetab();
        //System.out.println(getContent("https://mp.weixin.qq.com/s?src=11&timestamp=1510382527&ver=507&signature=G7R57utozQ-4eFVnMRQLKMocw7kWha1SdIY5Yby6t4PqGQObcfQHZrmiQZhZwF94zGH0VxPGW-Xgf16nN-ktQfLfS1DsaRcPV3ufQx82CuWfvSj-S*ThVQykkfx5J48U&new=1"));
    }

    @RequestMapping(value = "/getTabType", method = RequestMethod.POST)
    public static Map<String, Object> getTypetab(){
        String url = "http://weixin.sogou.com";
        Map<String, Object> res = new HashMap<>();
        List<Map<String, Object>> list = new ArrayList<>();
        try {
            Document doc = Jsoup.connect(url).ignoreContentType(true).timeout(5000).get();
            Elements types = doc.select("div.tab-box div a");
//            Elements types2 = doc.select("div.tab-box div div a");

            String[] ex_id = new String[]{"4","5","13","15","17","18","19"};
            Map<String, Object> d;
            for (Element type : types) {
                String id = type.select("a").attr("abs:id");
                id = id.substring(id.lastIndexOf("_")+1);
                String name = type.select("a").text();
                if(Arrays.asList(ex_id).contains(id)||name.equals("更多")){
                    continue;
                }
                d = new HashMap<>();
                d.put("id",id);
                d.put("name",name);
                list.add(d);
            }
            res.put("list",list);
            res.put("code",0);
        } catch (IOException e) {
            e.printStackTrace();
            res.put("code",1);

        }
        return res;
    }

    @RequestMapping(value = "/getContent", method = RequestMethod.POST)
    public static String getContent(String url) {
        url = URLUtils.URLRecode(url);
        Document doc = null;
        try {

            doc = Jsoup.connect(url).ignoreContentType(true)
                    // .header("User-Agent","Mozilla/5.0 (iPhone; CPU iPhone OS
                    // 10_2 like Mac OS X) AppleWebKit/602.3.12 (KHTML,
                    // likeGecko) Mobile/14C92 MicroMessenger/6.5.1
                    // NetType/WIFILanguage/zh_CN")
                    .header("User-Agent",
                            "Mozilla/5.0 (iPhone; CPU iPhone OS 10_2 like Mac OS X; zh-CN) AppleWebKit/537.51.1 (KHTML, like Gecko) Mobile/14C92 UCBrowser/11.3.0.895 Mobile  AliApp(TUnionSDK/0.1.6)")
                    .get();

            Elements e = doc.select("script");
            for (Element element : e) {// 替换script绝对地址
                // if (element.attr("src") != null &&
                // !element.attr("src").isEmpty()) {
                element.attr("src", element.absUrl("src"));
                // }

            }

            Elements e1 = doc.select("link");
            for (Element element : e1) {// 替换css绝对地址
                if (element.attr("href") != null
                        && !element.attr("href").isEmpty()) {
                    element.attr("href", element.absUrl("href"));
                }
            }

            Elements e2 = doc.select("img");
            for (Element element : e2) {// 替换图片资源绝对地址
                if (element.attr("src").trim().lastIndexOf("data") == -1) {
                    element.attr("src", element.absUrl("src"));
                }
                if (element.attr("src") != null
                        && element.attr("src").isEmpty()) {
                    element.attr("src",
                            "http://read.html5.qq.com/image?src=forum&q=5&r=0&imgflag=7&imageUrl="
                                    + element.absUrl("data-src"));
                    if (element.attr("data-src") != null
                            && !element.attr("data-src").isEmpty()
                            && !element.attr("src").isEmpty())
                        element.removeAttr("data-src");
                }
            }

            Elements e3 = doc.select("a");
            for (Element element : e3) {// 替换a标签绝对地址
                if (element.attr("href").trim().lastIndexOf("/") != -1
                        && element.attr("href").trim()
                        .lastIndexOf("javascript") == -1) {
                    element.attr("href", element.absUrl("href"));
                }
            }

            Elements e4 = doc.select("form");
            for (Element element : e4) {// 替换form表单绝对地址（跨域暂时无法解决，可无视）
                if (element.attr("action") != null
                        && !element.attr("action").isEmpty()) {
                    element.attr("action", element.absUrl("action"));
                }
            }

            Elements e6 = doc.select("meta");
            boolean falg = false;
            for (int i = 0; i < e6.size(); i++) {// 微信文章图片防盗链（跳板）
                if (e6.get(i).attr("name") != null
                        && !e6.get(i).attr("name").equals("referrer")) {
                    if (i >= e6.size() - 1) {
                        falg = true;
                    } else {
                        falg = false;
                    }
                } else {
                    break;
                }
                if (falg) {
                    e6.get(0).append(
                            "<meta name=\"referrer\" content=\"no-referrer\" >");
                    break;
                }
            }

            Elements e7 = doc.select("qqmusic");
            for (Element element : e7) {// 替换qqmusic绝对地址
                // if (element.attr("src") != null &&
                // !element.attr("src").isEmpty()) {
                element.attr("src", element.absUrl("src"));
                // }
            }

            Elements e8 = doc.select("iframe");
            for (Element element : e8) {// 替换iframe的src-data绝对地址
                if (element.attr("src").trim().lastIndexOf("data") == -1) {
                    element.attr("src", element.absUrl("src"));
                }
                if (element.attr("src") != null
                        && element.attr("src").isEmpty()) {
                    element.attr("src", element.absUrl("data-src"));
                    if (element.attr("data-src") != null
                            && !element.attr("data-src").isEmpty()
                            && !element.attr("src").isEmpty())
                        element.removeAttr("data-src");
                }
            }

            Element eArticle = doc.select("div#js_article").first();
            //System.out.println(eArticle);
            return eArticle.toString();
            //return doc.html();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

}
